# -*- coding:utf-8 -*-
from Orm.exceptions import ArgStructErr
import importlib


class QueryBuilder(object):
    TYPE_QUERY = "select"
    TYPE_UPDATE = "update"
    TYPE_INSERT = "insert"
    TYPE_DELETE = "delete"

    def __init__(self, sql_type=TYPE_QUERY, is_debug=False):
        self._model = None
        self._table = None
        self._update_field = None
        self._insert_data = None
        self._query_obj = None
        self._is_debug = is_debug if isinstance(is_debug, bool) else False
        self._sql_type = sql_type

    def set_table(self, value):
        self._table = value
        return self

    def set_sql_type(self, sql_type):
        if sql_type not in [self.TYPE_QUERY, self.TYPE_UPDATE, self.TYPE_INSERT, self.TYPE_DELETE]:
            raise ArgStructErr('sql type is invalid')
        self._sql_type = sql_type
        return self

    def set_debug(self, value):
        self._is_debug = value if isinstance(value, bool) else False
        return self

    def get_query_obj(self):
        if not self._query_obj:
            module_name = 'Orm.crud_builder'
            module = importlib.import_module(module_name)
            self._query_obj = getattr(module, self._sql_type.capitalize())(self)
        self._query_obj.table(self._table)
        return self._query_obj

    def set_model(self, model):
        self._model = model
        return self

    def exec_sql(self, sql, params):
        conn = self._model.get_connector().set_debug(self._is_debug)
        return conn.exec_sql(sql, params)

    def run(self):
        return self._model.get_connector().set_debug(self._is_debug).execute(self.get_query_obj())

    def __getattr__(self, item):
        if hasattr(self.get_query_obj(), item):
            return getattr(self.get_query_obj(), item)
